﻿#region References
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using JigLibX.Physics;
using JigLibX.Collision;
using JigLibX.Geometry;
using Xen;
using Ness.Engine.GUI;
using JigLibX.Math;
#endregion

namespace Ness.Engine.Entities
{
    /// <summary>
    /// All dynamic and static props are handled through this class.
    /// </summary>
    class Prop : Entity, IUpdate
    {
        #region Public variables
        public bool applyPhysics;
        public Body PhysicsBody { get { return body; } }
        public CollisionSkin PhysicsSkin { get { return collision; } }
        public Vector3 scale = Vector3.One;
        public Body body;
        public CollisionSkin collision;
        #endregion

        #region Private variables

        #endregion

        /// <summary>
        /// Iniialises the prop, adds physics and collision data
        /// </summary>
        public Prop(Engine game, string model, bool physics, bool applyLights)
            : base(game, model, applyLights)
        {
            //Set base variables
            this.applyPhysics = physics;
            this.game = game;
        }

        /// <summary>
        /// Sets the mass of the entity
        /// </summary>
        /// <param name="mass"></param>
        /// <returns></returns>
        protected Vector3 SetMass(float mass)
        {
            PrimitiveProperties primitiveProperties =
                new PrimitiveProperties(PrimitiveProperties.MassDistributionEnum.Solid, PrimitiveProperties.MassTypeEnum.Density, mass);

            float junk; Vector3 com; Matrix it, itCoM;

            collision.GetMassProperties(primitiveProperties, out junk, out com, out it, out itCoM);
            body.BodyInertia = itCoM;
            body.Mass = junk;

            return com;
        }

        /// <summary>
        /// Updates the props world position and physics
        /// </summary>
        /// <param name="state">Passed automatically. Ignore.</param>
        /// <returns>UpdateFrequency.FullUpdate60hz</returns>
        UpdateFrequency IUpdate.Update(UpdateState state)
        {
            if (PhysicsBody != null)
            {
                Matrix nMat;
                MoveTo(PhysicsBody.Position);

                if (body.CollisionSkin != null)
                    nMat = Matrix.CreateScale(scale) * body.CollisionSkin.GetPrimitiveLocal(0).Transform.Orientation * body.Orientation * Matrix.CreateTranslation(body.Position);
                else
                    nMat = Matrix.CreateScale(scale) * body.Orientation * Matrix.CreateTranslation(body.Position);

                if (WorldMatrix != nMat) WorldMatrix = nMat;
            }
            return UpdateFrequency.FullUpdate60hz;
        }
    }
}
